package Particles
{
	import Tools.BitmapTool;
	import Tools.DisplayTool;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;

    public class Particle
	{
        public var frames:Array=[];
        public var blend:String = "";
        public var duration:int = 0;
        public var layer:ParticleLayer;
        public var obj:Bitmap;
        public var x:Number = 0;
        public var y:Number = 0;
        public var animSpeed:Number = 0;
        public var deathCallback:Function = null;
		public var animFrame:Number=0;
        public var removed:Boolean = false;
        public var ticks:Number = 0;
		public var handleX:Number=0;
		public var handleY:Number=0;
		private var lastFrame:BitmapData;
		public var index:int=0;

        public function Particle()
		{
			super();
			obj=new Bitmap();
        }
        public final function update():void
		{
			ticks++;
			$update();
			_update();
        }
		protected function $update():void
		{
			if (blend != "")
			{
				obj.blendMode = blend;
			}
			syncFrame();
			if(frames.length>0)
			{
				if(Math.floor(animFrame)>frames.length-1)
				{
					remove();
				}
			}
			else
			{
				if(ticks>duration&&duration>0)
				{
					remove();
				}
			}
		}
		private function syncFrame():void
		{
			if (frames.length>0)
			{
				animFrame = animFrame + 1 / animSpeed;
				var frame:int= Math.floor(animFrame) % frames.length;
				setImage(frames[frame]);
			}
		}
		protected function _update():void
		{
			DisplayTool.moveTo(obj,x,y,handleX,handleY);
		}
		public function get bitmap():Bitmap
		{
			return obj as Bitmap;
		}
		public function setImage(bitmapData:BitmapData):void
		{
			if (bitmapData == lastFrame)
			{
				return;
			}
			bitmap.bitmapData = bitmapData;
			lastFrame = bitmapData;
		}
		public function initImage(imageData:Object):void
		{
			var bitmapData:BitmapData;
			bitmapData=BitmapTool.getImageByData(imageData);
			setImage(bitmapData);
		}
		public final function remove():void
		{
			if (deathCallback)
			{
				deathCallback(this);
			}
			if(obj.parent)
			{
				obj.parent.removeChild(obj);
			}
			_remove();
			removed=true;
			layer.toSyncRemoved=true;
		}
		protected function _remove():void
		{
			
		}
    }
}